<?php

namespace App\Http\Controllers;


use App\Comment;
use App\Discuss;
use App\Http\Requests;
use App\Solve;
use App\Task;
use App\User;
use App\Link;
use App\Utils;
use App\Parsedown;
use Auth;
use Cookie;
use DB;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Input;
use Log;
use Redirect;
use View;

class wellController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        //
    }

    public function rank(Request $request)
    {
        Utils::log($request, 'rank');
        $page = 1;
        $input = $request->all();
        if (isset($input['page']))
            $page = $request->all()['page'];
        $userlist = User::where('score', '>', 0)->orderBy('score', 'desc')->paginate(20);
        foreach ($userlist as $userdata) {
            $medaldata = DB::select('select class,title from medals where userid=' . $userdata['id']);
            $userdata['medals'] = $medaldata;
        }
        $type = "rank";
        return View::make('projects.rank')
            ->with(compact('userlist'))
            ->with(compact('type'))
            ->with(compact('page'));
    }

    public function agent(Request $request)
    {
        $agent = $request->server('HTTP_USER_AGENT');
        if (strpos("qlcoder spider", $agent) !== false) {
            echo("恭喜你,这题的答案是[Robots Exclusion Protocol]。");
        } else {
            echo("oh no,你现在来自<br>[" . $agent . "]<br> 这么机密的文件...我只会给来自于[qlcoder spider]的用户看的啦...");
        }
    }

    public function fs(Request $request)
    {
        $res = array();
        $res['success'] = false;
        $res['result'] = "";
        $answer = $request->all()["answer"];
        if ($answer == 3500) {
            $res['success'] = true;
            $res['result'] = " 恭喜你，答案正确！你已成功解锁<a href='/home'>4个新任务</a>！";
            setcookie("fs", true);
            setcookie("tn", 4);
        } else
            $res['result'] = "抱歉，答案错误";

        return response()->json($res);
    }

    public function welcome(Request $request)
    {
        Utils::log($request, 'welcome');
        $input = $request->all();
        if (!isset($input['utm'])) $input['utm'] = "unknown";
        $utm = $input['utm'];
        Log::info('come ' . $input['utm'] . ' ' . $request->getClientIp());
        return View::make("test/index")->with(compact('utm'));
    }

    public function first(Request $request)
    {
        $tasks = Task::all();
        $links = Link::all();
        $solve = array();
        foreach ($tasks as $task) {
            $solve[$task->id] = 0;
        }
        if (isset($_COOKIE['fs']))
            $solve[1] = 1;

        $tn = 0;
        foreach ($links as $link) {
            if ($solve[$link->second] == 1) continue;
            if ($solve[$link->first] == 1) {
                $solve[$link->second] = 2;
            }
        }
        if ($solve[1] == 0) $solve[1] = 2;
        $type = 'tree';
        return View::make('projects.first')
            ->with(compact('solve'))
            ->with(compact('tasks'))
            ->with(compact('links'))->with(compact('type'));
    }

    public function morenote(Request $request)
    {
        $input = $request->all();
        $id = $input['id'];
        $id = 1;
        $num = $input['num'];
        $comments = Comment::wheretaskidAndDelete($id, 0)->
        orderBy('updated_at', 'desc')->skip($num * 20)->take(20)->get();
        foreach ($comments as $comment) {
            $user = User::find($comment->userid);
            $comment->url = $user->avatar->url('thumb');
            if ($comment->url == "/avatars/thumb/missing.png") $comment->url = '/uploads/144086480364117.png';
            $comment->ruser = User::find($comment->ruserid);
        }
        return response()->json($comments);
    }


    public function show(Request $request, $id)
    {

        Utils::log($request, 'task');

        if (isset($_COOKIE['tn'])) {
            $tn = intval($_COOKIE['tn']);
            setcookie("tn", 0);
        }

        $id = Utils::url2id($id);
		if($id==143||$id==146)return;
        $task = Task::findOrFail($id);

        $author = User::find($task->contributor);
        $dis = Discuss::whereTitle($task->title . "的学习资料")->get();
        if (Auth::check()) {
            $userId = Auth::user()->id;
            $solve = Solve::whereUseridAndTaskidAndType($userId, $id, 0)
                ->get();
            $issolve = true;
            if (count($solve) == 0) $issolve = false;
        } else {
            $issolve = false;
            if (isset($_COOKIE['fs']) && $id == 1) {
                $issolve = true;
            }
        }
        Cookie::queue('这题的答案是oreo', '');

        $comments = Comment::wheretaskidAndDeleteAndType($id, 0, 0)->
        orderBy('updated_at', 'desc')->take(50)->get();
        foreach ($comments as $comment) {
            $user = User::find($comment->userid);
            $comment->user = $user;
            $comment->url = $user->avatar->url('thumb');
            $comment->ruser = User::find($comment->ruserid);
        }
        $user = Auth::user();
        $type = "";
        if ($id == 25 || $id == 41 || $id == 44 || $id == 72 || $id == 73 || $id == 76 || $id == 80 || $id == 90 || $id == 95 ||$id ==133||$id==140||$id==142) {
            if ($id == 25)
                $rankusers = DB::select('select userid,max(score) as score,max(rscore) as rscore from solves where taskid=25 and type=0 group by userid order by score desc,created_at asc');
            else if ($id == 41)
                $rankusers = DB::select('select userid,min(score) as score,max(rscore) as rscore from solves where taskid=41 and type=0 group by userid order by score asc,created_at asc');
            else if ($id == 72)
                $rankusers = DB::select('select userid,min(score) as score,max(rscore) as rscore from solves where taskid=72 and type=0 group by userid order by score asc,created_at asc');
            else if ($id == 73)
                $rankusers = DB::select('select userid,min(score) as score,max(rscore) as rscore from solves where taskid=73 and type=0 group by userid order by score asc,created_at asc');
            else if ($id == 76)
                $rankusers = DB::select('select userid,min(score) as score,max(rscore) as rscore from solves where taskid=76 and type=0 group by userid order by score asc,created_at asc');
            else if ($id == 44)
                $rankusers = DB::select('select userid,max(score) as score,max(score)*100 as rscore from solves where taskid=44 and type=0 group by userid order by score desc,created_at asc');
            else if ($id == 80)
                $rankusers = DB::select('select userid,max(score) as score,max(score)*100 as rscore from solves where taskid=80 and type=0 group by userid order by score desc,created_at asc');

            else if ($id == 90)
                $rankusers = DB::select('select userid,max(score) as score,max(score) as rscore from solves where taskid=90 and type=0 group by userid order by score desc,created_at asc');

            else if ($id == 95)
                $rankusers = DB::select('select userid,sum(score) as score,max(rscore) as rscore from solves where taskid=95  group by userid order by score desc,created_at asc');
			else if ($id == 133)
                $rankusers = DB::select('select userid,min(score) as score,max(rscore) as rscore from solves where taskid=133 and type=0 group by userid order by score asc,created_at asc');
			else if ($id == 140)
                $rankusers = DB::select('select userid,min(score) as score,max(rscore) as rscore from solves where taskid=140 and type=0 group by userid order by score asc,created_at asc');
			else if ($id == 142)
                $rankusers = DB::select('select userid,min(score) as score,max(rscore) as rscore from solves where taskid=142 and type=0 group by userid order by score asc,created_at asc');


            foreach ($rankusers as $rankuser) {
                $rankuser->name = User::find($rankuser->userid)->name;
            }
        }
		$Parsedown = new Parsedown();
        $task->material = $Parsedown->text($task->material);
       // $input['material'] = $Parsedown->text($input['material']);

        $techleadids = DB::select("select distinct(techleadid) from jobs where taskid=".$id);
        $techleadidsStr = "";
        $ok = false;
        foreach($techleadids as $k=>$v){
            if($ok) $techleadidsStr .= ",";
            $techleadidsStr .= $v->techleadid;
            $ok = true;
        }
		$techleads = array();
        if(count($techleadids)>0) $techleads = DB::select("select * from techleads where id in (".$techleadidsStr.")");
		foreach($techleads as $techlead){
			$companies = DB::select("select * from companies where id =".$techlead->companyid);
			if(count($companies)==0) continue;
			$company = $companies[0];
            $techlead->company = $company->name;
            $techlead->slogan = $company->slogan;
        }

        return View::make('tasks.index3')
            ->with(compact('task'))
            ->with(compact('user'))
            ->with(compact('type'))
            ->with(compact('tn'))
            ->with(compact('comments'))
            ->with(compact('dis'))
            ->with(compact('author'))
            ->with(compact('rankusers'))
            ->with(compact('issolve'))
            ->with(compact('techleads'))
            ->with(compact('issolve'));
    }

    public function log()
    {
        return View::make("timeline.index");
    }

    public function download(Request $request, $file)
    {
        if ($file == 'hugefile') {
            $str = $request->headers->get('Range');
            if ($str == null || strpos($str, 'bytes') === false) {
                echo '这个文件100G,亲你真想下从头开始下完它么= =!';
            } else {
                echo '这题的答案是 content-range';
            }
        } else
            return response()->download("uploads/" . $file);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function spamrank(Request $request)
    {
        var_dump("123");   //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request $request
     * @return Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return Response
     */

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request $request
     * @param  int $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return Response
     */
    public function destroy($id)
    {
        //
    }
}
